package com.lb.activity.service.impl;

import com.lb.activity.mapper.PermissionMapper;
import com.lb.activity.mapper.RolePermissionMapper;
import com.lb.activity.po.Permission;
import com.lb.activity.po.RolePermission;
import com.lb.activity.service.PermissionService;
import com.lb.activity.util.BuildTree;
import com.lb.activity.util.PermissionTree;
import com.lb.activity.util.ResultUtil;
import com.lb.activity.util.SnowflakeIdWorker;
import com.lb.activity.util.emumdata.DataEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liubin
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private SnowflakeIdWorker idWorker;

    @Override
    public List<Permission> AllMeuns() {
        Example example = new Example(Permission.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", DataEnum.DELETE_STATUS.getStatus());
        List<Permission> permissions = permissionMapper.selectByExample(example);
        return permissions;
    }

    @Override
    public ResultUtil add(Permission permission) {
        if(permission.getParentid()==null){
            permission.setParentid((long)0);
        }
        if(permission.getId()==null){
            permission.setId(idWorker.nextId());
            permissionMapper.insertSelective(permission);
        }else{
            permissionMapper.updateByPrimaryKeySelective(permission);
        }
        return ResultUtil.ok();
    }

    @Override
    public Permission getOne(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }


    @Override
    public ResultUtil delete(Long id) {
        // 判断当前是否有角色使用该权限
        boolean check = roleHasPermission(id);
        if(check){
            return ResultUtil.build(400,"已经有角色拥有该权限，不能删除");
        }
        // 判断当前权限是否有子菜单
        Example examplePer = new Example(Permission.class);
        Example.Criteria perCriteria = examplePer.createCriteria();
        perCriteria.andEqualTo("parentid",id);
        List<Permission> permissions = permissionMapper.selectByExample(examplePer);
        for (Permission permission : permissions) {
            boolean checkChild = roleHasPermission(permission.getId());
            if(checkChild){
                return ResultUtil.build(400,"已经有角色拥有该权限，不能删除");
            }else{
                //执行删除（更新操作）
                permission.setStatus(Integer.parseInt(DataEnum.DELETE_STATUS.getStatus()+""));
                updatePermission(permission);
            }
        }
        //更新
        Permission permission = Permission.builder().id(id).status(Integer.parseInt(DataEnum.DELETE_STATUS.getStatus()+"")).build();
        updatePermission(permission);

        return ResultUtil.ok();
    }

    /**
     * 检查状态 ，否是有角色拥有该权限
     * @param permissionId
     * @return
     */
    public boolean roleHasPermission(Long permissionId){
        Example example = new Example(RolePermission.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("permissionid",permissionId);
        List<RolePermission> rolePermissions = rolePermissionMapper.selectByExample(example);
        if(rolePermissions.size() > 0){
            return true;
        }
        return false;
    }

    /**
     * 更新
     * @param permission
     */
    public void updatePermission(Permission permission){
        permissionMapper.updateByPrimaryKeySelective(permission);
    }

    @Override
    public ResultUtil changeStatus(Long id, boolean boolStatus) {
        return null;
    }

    @Override
    public ResultUtil getOneByName(String name, Long id) {
        Example example = new Example(Permission.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", DataEnum.DELETE_STATUS.getStatus());
        criteria.andEqualTo("name",name);
        if(id != null){
            criteria.andNotEqualTo("id",id);
        }
        List<Permission> permissions = permissionMapper.selectByExample(example);
        if(permissions.size() > 0){
            ResultUtil.build(400,"名称已经存在");
        }
        return ResultUtil.ok();
    }

    @Override
    public PermissionTree<Permission> getTree(Long roleId) {
        //查询所有的权限菜单
        List<Permission> storeAdminPermissions = getMeunsList();
        //获取该角色所拥有的权限caidan
        List<Long> menuIds = permissionMapper.listMenuIdByRoleId(roleId);
        List<Long> temp = menuIds;
        for (Permission menu : storeAdminPermissions) {
            if (temp!=null&&temp.size()>0&&temp.contains(menu.getParentid())) {
                menuIds.remove(menu.getParentid());
            }
        }
        List<PermissionTree<Permission>> trees = new ArrayList<>();
        //List<StoreAdminPermission> StoreAdminPermissions = getMeunsList();
        for (Permission storeAdminPermission : storeAdminPermissions) {
            PermissionTree<Permission> tree = new PermissionTree<>();
            tree.setId(storeAdminPermission.getId().toString());
            tree.setParentId(storeAdminPermission.getParentid().toString());
            tree.setText(storeAdminPermission.getName());
            Map<String, Object> state = new HashMap<>(1);
            Long menuId = storeAdminPermission.getId();
            if (menuIds!=null&&menuIds.size()>0&&menuIds.contains(menuId)) {
                state.put("selected", true);
            } else {
                state.put("selected", false);
            }
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        PermissionTree<Permission> t = BuildTree.build(trees);
        return t;
    }

    @Override
    public void updateRoleAndmenuIds(Long roleId, List<String> menuIds) {
        permissionMapper.removeByRoleId(roleId);
        List<RolePermission> storeRolePermissions = new ArrayList<>();
        for (String  menuId: menuIds) {
            RolePermission storeRolePermission= new RolePermission();
            storeRolePermission.setId(idWorker.nextId());
            storeRolePermission.setRoleid(roleId);
            storeRolePermission.setPermissionid(Long.valueOf(menuId));
            storeRolePermission.setStatus(Integer.parseInt(DataEnum.INSERT_STATUS.getStatus()+""));
            storeRolePermissions.add(storeRolePermission);
        }
        if (storeRolePermissions.size() > 0) {
            rolePermissionMapper.batchSave(storeRolePermissions);
        }
    }

    @Override
    public List<PermissionTree<Permission>> listMenuTree(Long userId) {
        List<PermissionTree<Permission>> trees = new ArrayList<PermissionTree<Permission>>();
        List<Permission> storeAdminPermissions= permissionMapper.listMenuByUserId(userId);
        for (Permission storeAdminPermission : storeAdminPermissions) {
            PermissionTree<Permission> tree = new PermissionTree<Permission>();
            tree.setId(storeAdminPermission.getId().toString());
            tree.setParentId(storeAdminPermission.getParentid().toString());
            tree.setText(storeAdminPermission.getName());
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("url", storeAdminPermission.getUrl());
            attributes.put("icon", storeAdminPermission.getIcon());
            tree.setAttributes(attributes);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        List<PermissionTree<Permission>> list = BuildTree.buildList(trees, "0");
        return list;
    }

    @Override
    public Permission getPermission(Long permissionid) {
        return permissionMapper.selectByPrimaryKey(permissionid);
    }

    /**
     * 查询所有合法的菜单
     */
    public List<Permission> getMeunsList() {
        Example example = new Example(Permission.class);
        example.setOrderByClause(" sort asc");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",Integer.parseInt(DataEnum.INSERT_STATUS.getStatus()+""));
        return permissionMapper.selectByExample(example);
    }

}
